package controller.info;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.Session;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pojo.Devuser;
import pojo.Info;
import pojo.Version;
import service.info.InfoService;
import service.version.VersionService;
import tool.Special;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("info")
public class InfoController {

 @Resource
    private InfoService infoService;
    @Resource
    private VersionService versionService;
    //跳转到后台查询页面的方法
    @RequestMapping("/toaudit")
    public String toaudit(){
        return "redirect:/info/getAppInfoList";
    }

    //跳转到后台查询页面
    @RequestMapping("/tolist")
    public String tolist(){
        return "audit";
    }

    //跳转到后台查询页面的回显页面
    @RequestMapping("/huiXian")
    public String huiXian(Integer id,Model model){
        Info info=infoService.getHuiXian(id);
        model.addAttribute("app",info);
        return "show";
    }
    //跳转到后台查询页面进行查询
    @RequestMapping("/getAppInfoList")
    public String getAppInfoList( @RequestParam(defaultValue = "1") Integer pageIndex, String softwareName, String flatformId , @RequestParam(defaultValue = "0")String categoryLevel1, @RequestParam(defaultValue = "0")String categoryLevel2, @RequestParam(defaultValue = "0")String categoryLevel3, HttpServletRequest request){
       int count=infoService.count(softwareName, flatformId, categoryLevel1, categoryLevel2, categoryLevel3);
        int totalPage=count%5==0?count/5:count/5+1;
        List<Info> infoPageList = infoService.getAppInfoList((pageIndex-1)*5,5,softwareName, flatformId, categoryLevel1, categoryLevel2, categoryLevel3);
        request.setAttribute("infoPageList",infoPageList);
        request.setAttribute("totalPage",totalPage);
        request.setAttribute("pageIndex",pageIndex);
        request.setAttribute("softwareName",softwareName);
        request.setAttribute("flatformId",flatformId);
        request.setAttribute("categoryLevel1",categoryLevel1);
        request.setAttribute("categoryLevel2",categoryLevel2);
        request.setAttribute("categoryLevel3",categoryLevel3);
        return "audit";
    }
    //跳转到开发者查询页面的方法
    @RequestMapping("/touserKaiaudit")
    public String userKaiaudit(){
        return "redirect:/info/getuserKaiauditList";
    }
    //跳转到开发者查询页面进行查询
    @RequestMapping("/getuserKaiauditList")
    public String getuserKaiauditList(@RequestParam(required = false,defaultValue = "1") Integer pageIndex, String softwareName, String flatformId , @RequestParam(defaultValue = "0")String categoryLevel1,@RequestParam(defaultValue = "0") String categoryLevel2,@RequestParam(defaultValue = "0") String categoryLevel3,String status, HttpServletRequest request){
        int count=infoService.userKaicount(softwareName, flatformId, categoryLevel1, categoryLevel2, categoryLevel3,status);
        int totalPage=count%5==0?count/5:count/5+1;
        Devuser devuser = (Devuser)request.getSession().getAttribute("devuser");
        int id = devuser.getId();

        String keyword = "";
        if (!"".equals(softwareName) && softwareName != null) {
            keyword = Special.specialStr(softwareName);// 排除%等通配符

        }
        List<Info> infoPageList = infoService.getuserKaiAppInfoList((pageIndex-1)*5,5,keyword, flatformId, categoryLevel1, categoryLevel2, categoryLevel3,status,id);
        request.setAttribute("infoPageList",infoPageList);
        request.setAttribute("totalPage",totalPage);
        request.setAttribute("pageIndex",pageIndex);
        request.setAttribute("softwareName",softwareName);
        request.setAttribute("flatformId",flatformId);
        request.setAttribute("status",status);
        request.setAttribute("categoryLevel1",categoryLevel1);
        request.setAttribute("categoryLevel2",categoryLevel2);
        request.setAttribute("categoryLevel3",categoryLevel3);
        return "userKaiaudit";
    }

    //跳转到开发者新增页面
    @RequestMapping("/toAddXinxi")
    public String toAddXinxi(){
        return "addAppInfo";
    }

    //新增开发者的方法
    @RequestMapping("/addAppInfoList")
    public String addAppInfoList(Info info,HttpServletRequest request, @RequestParam(value = "idPic",required = false) MultipartFile idPic){
        String idPicPath=null;
        String path=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
        if(!idPic.isEmpty()){
            String originalFile=idPic.getOriginalFilename();
            String prefix= FilenameUtils.getExtension(originalFile);
            int filesize=5000000;
            if(idPic.getSize()>filesize){
                request.setAttribute("uploadFileError","*daxiao");
                return "addAppInfo";
            }else if(prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")||prefix.equalsIgnoreCase("jpeg")||prefix.equalsIgnoreCase("pneg")) {
                String fileName = System.currentTimeMillis() + RandomUtils.nextInt(10000000) + "_Personal." + prefix;
                File tragetFile = new File(path);
                if (!tragetFile.exists()) {
                    tragetFile.mkdirs();
                }
                try {
                    idPic.transferTo(new File(tragetFile, fileName));
                } catch (Exception e) {
                    e.printStackTrace();
                    request.setAttribute("uploadFileError", "上传失败！");
                        return "addAppInfo";
                }
                idPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
            }else{
                request.setAttribute("uploadFileError","格式不正确");
                return "addAppInfo";
            }
        }
        info.setLogoLocPath(path);
        info.setCreationDate(new Date());
        info.setDevId(((Devuser)request.getSession().getAttribute("devuser")).getId());
        info.setLogoPicPath(idPicPath);
        int num=infoService.addAppInfoList(info);
        if(num>0){
            return "redirect:/info/getuserKaiauditList";
        }else{
            return "addAppInfo";
        }
    }

    //修改开发者的回显方法
    @RequestMapping("/getAppInfohuiXian")
    public String getAppInfohuiXian(Model model,@RequestParam("id") int id){
        Info info=infoService.getAppInfohuiXian(id);
        model.addAttribute("info",info);
        return "updateAppInfo";
    }

    //修改开发者的方法
    @RequestMapping("/updateAppInfoList")
    public String updateAppInfoList(Info info,HttpServletRequest request, @RequestParam(value = "idPic",required = false) MultipartFile idPic){
        String idPicPath=null;
        String path=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
        if (idPic!=null) {
            if(!idPic.isEmpty()){
                String originalFile=idPic.getOriginalFilename();
                String prefix= FilenameUtils.getExtension(originalFile);
                int filesize=5000000;
                if(idPic.getSize()>filesize){
                    request.setAttribute("uploadFileError","*daxiao");
                    return "updateAppInfo";
                }else if(prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("pang")||prefix.equalsIgnoreCase("jpeg")||prefix.equalsIgnoreCase("pneg")) {
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(10000000) + "_Personal." + prefix;
                    File tragetFile = new File(path);
                    if (!tragetFile.exists()) {
                        tragetFile.mkdirs();
                    }
                    try {
                        idPic.transferTo(new File(tragetFile, fileName));
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute("uploadFileError", "上传失败！");
                        return "updateAppInfo";
                    }
                    idPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                }else{
                    request.setAttribute("uploadFileError","格式不正确");
                    return "updateAppInfo";
                }
                info.setLogoLocPath(path);
                info.setLogoPicPath(idPicPath);
            }
        }


        info.setCreationDate(new Date());
        info.setDevId(((Devuser)request.getSession().getAttribute("devuser")).getId());info.setStatus(1);
        int num=infoService.updateAppInfoList(info);
        if(num>0){
            return "redirect:/info/getuserKaiauditList";
        }else{
            return "updateAppInfo";
        }

    }
   //开发者APK名称的重名判断的方法
    @ResponseBody
    @RequestMapping(value = "APKchongMing",produces = {"application/json;charset=utf-8"})
    public Object APKchongMing(String APKName){
    Map map=new HashMap();
       if(infoService.APKchongMing(APKName)!=null){
           map.put("flag","cg");
        }
       else {
           map.put("flag","sb");
       }
    String s = JSON.toJSONString(map);
    return s;
    }
    //开发者手游名称的重名判断的方法
    @ResponseBody
    @RequestMapping(value = "softwareNamechongMing",produces = {"application/json;charset=utf-8"})
    public Object softwareNamechongMing(String softwareName){
        Map map=new HashMap();
        boolean falg;
        if(infoService.softwareNamechongMing(softwareName)!=null){
            map.put("flag","cg");
        }
        else {
            map.put("flag","sb");
        }
        String s = JSON.toJSONString(map);
        return s;
    }

    //删除功能
    @RequestMapping("/delxx")
    public String del(int id,HttpServletRequest request) throws Exception {
        List<Version> appVersionList=versionService.getAllAppVersion(id);
        for(Version version:appVersionList){
            if(version.getApkLocPath()!=null&&!version.getApkLocPath().equals("")){
                File file=new File(request.getSession().getServletContext().getRealPath("/")+version.getApkLocPath());
                if(file.exists()){
                    boolean delete1 = file.delete();
                    if (delete1) {
                        int a=1;
                    }
                }
            }
        }
        int i = infoService.delByVersionAppId(id);
        Info in = infoService.getAppInfohuiXian(id);
        int b=0;
        if(in.getLogoPicPath()!=null&&!in.getLogoPicPath().equals("")){
            File file=new File(request.getSession().getServletContext().getRealPath("/")+in.getLogoPicPath());
            if(file.exists()){
                boolean delete2 = file.delete();
                if (delete2) {
                    b++;
                }
            }
        }
        int i1 = infoService.delByInfoId(id);
        if(i1>0){
            return "userKaiaudit";
        }
        return "userKaiaudit";
    }
    //上架

    @RequestMapping("/shangjia")
    public String hsangjia(int id){
        int i = infoService.updateStatusshang(id);
        if (i>0) {
            return "";
        }
        return " ";
    }
    //下架
    @RequestMapping("/xiajia")
    public String xiajia(int id){
        int i = infoService.updateStatusxia(id);
        if (i>0) {
            return "";
        }
        return " ";
    }
    //通过审核
    @RequestMapping("/tongg")
    public String tongg(int id){
        infoService.updateStatusTrue(id);
        return "redirect:/info/toaudit";
    }
    //不通过审核
    @RequestMapping("/nutong")
    public String nutong(int id){
        infoService.updateStatusFalse(id);
        return "redirect:/info/toaudit";
    }
    //待审核
    @RequestMapping("/updateStatuszTai")
    public String updateStatuszTai(int id){
        infoService.updateStatuszTai(id);
        return "userKaiaudit";
    }

}